package dice.sinanya.listener;

import com.forte.qqrobot.anno.timetask.CronTask;
import com.forte.qqrobot.exception.TimeTaskException;
import com.forte.qqrobot.sender.MsgSender;
import com.forte.qqrobot.timetask.TimeJob;
import com.forte.qqrobot.utils.CQCodeUtil;
import dice.sinanya.db.update.MakeUpdateCache;
import dice.sinanya.exceptions.NotMasterException;
import dice.sinanya.system.MessagesSystem;
import dice.sinanya.tools.getinfo.SystemType;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;

import static dice.sinanya.SinaNya.runLevel;
import static dice.sinanya.SinaNya.systemType;
import static dice.sinanya.db.redis.GroupNode.makeVersion;
import static dice.sinanya.tools.getinfo.GetMessagesProperties.entityBanProperties;
import static dice.sinanya.tools.getinfo.GetMessagesProperties.entitySystemProperties;
import static dice.sinanya.tools.getinfo.MyDownLoadFromUrl.downloadFile;
import static dice.sinanya.update.UpdateForDice.checkNeedUpdate;
import static dice.sinanya.update.UpdateForDice.unZip;
import static dice.sinanya.windows.imal.HttpGet.sendGet;

/**
 * @author SitaNya
 * 日期: 2019-07-12
 * 电子邮箱: sitanya@qq.com
 * 维护群(QQ): 162279609
 * 有任何问题欢迎咨询
 * 类说明:
 */
@CronTask("0 0 12 * * ? *")
public class Update implements TimeJob {
    MsgSender msgSender;

    public Update() {
//        由于构造方法每次任务周期都会被调用，因此很多东西无法写在里面
    }

    @Override
    public void execute(MsgSender msgSender, CQCodeUtil cqCodeUtil) {
        this.msgSender = msgSender;
        try {
            String nextVersion = sendGet("https://dice-7-1256090486.file.myqcloud.com/version");
            boolean needUpdate = !MessagesSystem.VERSIONS.equals(nextVersion);
            boolean notWarn = !sendGet("https://dice-7-1256090486.file.myqcloud.com/version").contains("Alpha") && !sendGet("https://dice-7-1256090486.file.myqcloud.com/version").contains("Beta");
            boolean levelTest = Long.parseLong(makeVersion(MessagesSystem.VERSIONS)) < Long.parseLong(makeVersion(nextVersion));
            boolean result = needUpdate && notWarn && levelTest;
            if (result) {
                if (entitySystemProperties.isAutoUpdate() && new MakeUpdateCache().getUpdateCache()) {
                    updateAuto();
                } else {
                    for (String master : entityBanProperties.getMaster()) {
                        if (!"450609203".equals(master)) {
                            msgSender.SENDER.sendPrivateMsg(master, "最新版本为:\t" + sendGet("https://dice-7-1256090486.file.myqcloud.com/version") + "\n当前版本为:\t" + MessagesSystem.VERSIONS + "\n请进行更新，本通知固定于每日12点整发送一次");
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new TimeTaskException(e);
        }
    }

    private void updateAuto() throws NotMasterException, IOException {
        if (!checkNeedUpdate()) {
            return;
        }
        if (downUpdateZip(false)) {
            new MakeUpdateCache().makeUpdateCache();
            restart();
        }
    }

    public void restart() {
        String fileName = "SinaNya.exe";
        if (systemType.equals(SystemType.LINUX)) {
            fileName = "SinaNya";
        }
        switch (runLevel) {
            case CQA:
            case DEBUG:
            case CQP:
            case PDEBUG:
                new dice.sinanya.start.Update().run(fileName);
                System.exit(-1);
                break;
            default:
                msgSender.SENDER.sendPrivateMsg("450609203", "更新失败");
        }
    }

    private boolean downUpdateZip(boolean alpha) throws IOException {
        String dir = entitySystemProperties.getSystemDir("0");

        String url = "https://dice-7-1256090486.file.myqcloud.com/";
        if (alpha) {
            url = "https://dice-7-1256090486.file.myqcloud.com/";
        }

        File zip = new File(URLDecoder.decode(dir, "UTF-8"), "SinaNyaNext.zip");
        File oldNext = new File(URLDecoder.decode(dir, "UTF-8"), "update");
        boolean zipExists = zip.exists();
        boolean oldDirExists = oldNext.getParentFile().exists() && oldNext.getParentFile().isDirectory();
        if (zipExists) {
            zip.delete();
        }
        if (oldNext.exists()) {
            oldNext.delete();
        }

        if (!oldDirExists) {
            oldNext.getParentFile().delete();
            oldNext.getParentFile().mkdirs();
        }

        long zipSize = new URL(url + "SinaNyaNext.zip").openConnection().getContentLength();

        downloadFile(url + "SinaNyaNext.zip", zip, zipSize);
        zipExists = zip.exists();


        if (oldDirExists && zipExists && zip.length() == zipSize) {
            unZip(zip, oldNext.getPath());
            return true;
        } else {
            return false;
        }
    }
}